package com.yzz.composeweatherproject.activity

import androidx.compose.animation.AnimatedVisibility
import androidx.compose.foundation.interaction.*
import androidx.compose.foundation.layout.Row
import androidx.compose.foundation.layout.Spacer
import androidx.compose.foundation.layout.size
import androidx.compose.material.Button
import androidx.compose.material.ButtonDefaults
import androidx.compose.material.Text
import androidx.compose.runtime.*
import androidx.compose.ui.Modifier

/**
 * @Author : yangzuozhe
 * @Time : On 2022/5/29 1:01
 *
 * @Description : HandleInteractions
 */
@Composable
fun InteractionClick() {
    val interactionSource = remember { MutableInteractionSource() }
    val isPressed by interactionSource.collectIsPressedAsState()
    Button(
        onClick = { /* do something */ },
        interactionSource = interactionSource) {
        Text(if (isPressed) "Pressed!" else "Not pressed")
    }
}

@Composable
fun InteractionSource() {
    val interactionSource = remember {
        MutableInteractionSource()
    }
    val interactions = remember {
        mutableStateListOf<Interaction>()
    }
    val lastInteraction = when (interactions.lastOrNull()) {
        is DragInteraction.Start -> "Dragged"
        is PressInteraction.Press -> "Pressed"
        else -> "No state"
    }
    LaunchedEffect(interactionSource) {
        interactionSource.interactions.collect { interaction ->
            when (interaction) {
                is PressInteraction.Press -> {
                    interactions.add(interaction)
                }
                is PressInteraction.Release -> {
                    interactions.remove(interaction.press)
                }
                is PressInteraction.Cancel -> {
                    interactions.remove(interaction.press)
                }
                is DragInteraction.Start -> {
                    interactions.add(interaction)
                }
                is DragInteraction.Stop -> {
                    interactions.remove(interaction.start)
                }
                is DragInteraction.Cancel -> {
                    interactions.add(interaction.start)
                }
            }
        }
    }
}

@Composable
fun PressIconButton(
    onClick: () -> Unit,
    icon: @Composable () -> Unit,
    text: @Composable () -> Unit,
    modifier: Modifier = Modifier,
    interactionSource: MutableInteractionSource = remember { MutableInteractionSource() },
) {
    val isPress by interactionSource.collectIsPressedAsState()
    Button(onClick = onClick, modifier = modifier, interactionSource = interactionSource) {
        AnimatedVisibility(isPress) {
            if (isPress) {
                Row {
                    icon()
                    Spacer(modifier = Modifier.size(ButtonDefaults.IconSize))
                }
            }
        }
        text()
    }
}